package com.mvc.controller;

import com.db.dao.OrderRecordDao;
import com.db.dao.RestaurantDao;
import com.db.entity.OrderRecord;
import com.db.entity.Restaurant;
import com.db.utility.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created by MAGI on 2014/12/14.
 */

@Controller
@RequestMapping("/eat")
public class EatController {

    @Autowired
    private RestaurantDao restaurantDao;

    @Autowired
    private OrderRecordDao orderRecordDao;

    @RequestMapping("/main")
    public String eat(Model model) {
        List<Restaurant> rests = restaurantDao.findAll();
        Restaurant r = new Restaurant();
        r.setName("沙县小吃");
        rests.add(r);
        r.setName("高祖生煎");
        rests.add(r);
        model.addAttribute("rests", rests);

        return "eat/main";
    }

    @RequestMapping("/addRt")
    public void addRt(Restaurant rest , HttpServletResponse response) throws IOException {

        rest.setUuid(Tools.getUUID());
        boolean ok = restaurantDao.save(rest);
        String words;
        if(ok)
            words = "添加成功";
        else
            words = "添加失败";
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(words);
    }

    @RequestMapping("/addRd")
    public void addRd(OrderRecord record, HttpServletResponse response, HttpSession session) throws IOException {
        String words;
        response.setCharacterEncoding("UTF-8");


        String user = (String) session.getAttribute("username");
        if(user.trim().isEmpty())
        {
            words = "未登录";
            response.getWriter().write(words);
        }

        orderRecordDao.save(record);

        response.getWriter().write("添加成功");
    }


}
